<template>
  <div id="addPictureByUrl">
    <a-input-group compact>
      <a-input
        v-model:value="imgUrl"
        style="width: calc(100% - 120px)"
        placeholder="请输入图片url"
      />
      <a-button type="primary" style="width: 120px" :loading="loading" @click="handleUpload">
        提交
      </a-button>
    </a-input-group>
    <div class="img-wrapper">
      <img v-if="picture" :src="picture.url" alt="avatar" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { uploadPictureByUrlUsingPost } from '@/api/pictureController.ts'

const imgUrl = ref<string>()
const loading = ref<boolean>(false)

interface Props {
  picture?: API.PictureVO
  spaceId: string
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()
const handleUpload = async () => {
  loading.value = true
  const param: API.PictureUploadReq = {
    fileUrl: imgUrl.value,
  }
  if (props.picture) {
    param.id = props.picture.id
  }
  param.spaceId = props.spaceId
  const res = await uploadPictureByUrlUsingPost(param)
  message.success('上传成功')
  props.onSuccess(res.data)
  loading.value = false
}
</script>

<style scoped>
.addPictureByUrl {
  margin-bottom: 16px;
}

.addPictureByUrl img {
  max-width: 100%;
  max-height: 480px;
}

.img-wrapper {
  text-align: center;
  margin-top: 16px;
}

.img-wrapper img {
  max-width: 640px;
  object-fit: contain;
}
</style>
